package com.up.api.xianliu;


import com.up.redis.service.RedisCacheService;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.scripting.support.ResourceScriptSource;
import org.springframework.stereotype.Component;

import java.time.LocalTime;
import java.util.Arrays;

/**
 * @author: liuchengjun
 * @title: XianLiU
 * @projectName: 海联技术中台V2.0
 * @depart 软件事业部
 * @description:  https://www.wdbyte.com/java/rate-limiter/#1-%E9%99%90%E6%B5%81
 * @date: 2023/12/18/018 16:12 (星期一)
 * @since V2.0
 */
@Component
public class XianLiU {
    private String KEY_PREFIX = "limiter_";
    private String QPS = "50";
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private RedisCacheService redisCacheService;

    /**
     * 计数器限流
     *
     * @param key
     * @return
     */
    public boolean acquire(String key) {
        long now = System.currentTimeMillis();
        key = KEY_PREFIX + key;
        String oldest = String.valueOf(now - 1_000);
        String score = String.valueOf(now);
        String scoreValue = score;
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setResultType(Long.class);
        //lua文件存放在resources目录下
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("limiter2.lua")));
        return stringRedisTemplate.execute(redisScript, Arrays.asList(key), oldest, score, QPS, scoreValue) == 1;
    }
    public boolean redisHelloWorld(){
        return redisCacheService.set("helloWord", 1);
    }

}
